<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader
      :list="list"
      @addTodoList="addTodoList"
      @chnageIsAll="chnageIsAll"
    ></TodoHeader>
    <TodoMain
      :list="FindeList"
      @checkedId="checkedId"
      @deleteById="deleteById"
    ></TodoMain>
    <TodoFooter
      :list="list"
      @clearList="clearList"
      :type="type"
      @findList="findList"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";

import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("todoList")),
      type: "all", //all 显示全部 yes 显示已完成 no 显示未完成
    };
  },
  computed: {
    // 计算是否全部显示
    FindeList() {
      // debugger;
      if (this.type === "yes") {
        return this.list.filter((item) => item.isDone);
      } else if (this.type === "no") {
        return this.list.filter((item) => !item.isDone);
      } else {
        return this.list;
      }
    },
  },
  methods: {
    checkedId(id) {
      // 接收子组件传递过来的id，查找到相对应的id把isDone值取反
      const res = this.list.find((item) => item.id === id);
      res.isDone = !res.isDone;
    },
    deleteById(id) {
      // 能到子组件传递过来的id过滤
      this.list = this.list.filter((item) => item.id !== id);
    },
    addTodoList(Todolist) {
      // 接收子组件传递过来的值
      if (!Todolist) return;
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 0,
        name: Todolist,
        isDone: false,
      });
    },
    clearList() {
      // 清除已完成
      this.list = this.list.filter((item) => !item.isDone);
    },
    findList(TypeList) {
      // 筛选显示
      this.type = TypeList;
    },
    chnageIsAll(val) {
      console.log(val);
      this.list.forEach((item) => (item.isDone = val));
    },
  },
  watch: {
    // 监听list
    list: {
      deep: true,
      immediate: true,
      handler() {
        localStorage.setItem("todoList", JSON.stringify(this.list));
      },
    },
  },
};
</script>